package com.cloudfun.campusshare.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.cloudfun.campusshare.common.constant.Code;
import com.cloudfun.campusshare.common.constant.DeviceStatus;
import com.cloudfun.campusshare.common.constant.DeviceType;
import com.cloudfun.campusshare.common.constant.ReplenishStatus;
import com.cloudfun.campusshare.common.exception.BusinessException;
import com.cloudfun.campusshare.common.model.dto.ReplenishDTO;
import com.cloudfun.campusshare.common.model.dto.ReplenishLogDTO;
import com.cloudfun.campusshare.common.model.dto.ReplenishStatusCountDTO;
import com.cloudfun.campusshare.common.model.vo.ReplenishLogVO;
import com.cloudfun.campusshare.common.model.vo.ReplenishSettingVO;
import com.cloudfun.campusshare.common.model.vo.ReplenishVO;
import com.cloudfun.campusshare.common.model.vo.WashPointForQueryListVO;
import com.cloudfun.campusshare.common.response.BaseResult;
import com.cloudfun.campusshare.common.response.BaseResultFactory;
import com.cloudfun.campusshare.common.response.PageResult;
import com.cloudfun.campusshare.common.security.AuthenticationHolder;
import com.cloudfun.campusshare.entity.*;
import com.cloudfun.campusshare.repo.*;
import com.cloudfun.campusshare.service.ReplenishService;
import com.cloudfun.campusshare.service.UserRelService;
import com.cloudfun.campusshare.service.WashPointService;
import com.cloudfun.campusshare.util.BeanCopyUtil;
import com.cloudfun.campusshare.util.DateUtil;
import com.cloudfun.campusshare.util.ExcelUtils;
import com.cloudfun.campusshare.util.tencent.TencentSMSUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @author wangxiyuan
 * @description 补货模块service实现类
 * @createDate 2021/5/18 19:13
 **/
@Service
@Slf4j
@Transactional
public class ReplenishServiceImpl implements ReplenishService {
    @Autowired
    private ReplenishRepo replenishRepo;

    @Autowired
    private DeviceEntityRepo deviceEntityRepo;

    @Autowired
    private RepleinshLogRepo repleinshLogRepo;

    @Autowired
    private UserRelService userRelService;

    @Autowired
    private LiquidCapacitySettingRepo liquidCapacitySettingRepo;

    @Autowired
    private WashPointConcretePositionEntityRepo positionEntityRepo;

    @Autowired
    private UserRoleEntityRepo userRoleEntityRepo;

    @Autowired
    private UserRelEntityRepo userRelEntityRepo;

    @Autowired
    private UserEntityRepo userEntityRepo;

    @Autowired
    private WashPointService washPointService;

    // 洗衣液默认容量 单位g
    public static final int LAUNDRY_DETERGENT_CAPACITY = 5000;
    // 消毒液默认容量 单位g
    public static final int DISINFECTANT_CAPACITY = 5000;

    // 洗衣液阈值
    public static int LAUNDRY_DETERGENT_CAPACITY_THRESHOLD = 5000 / 4;

    // 消毒液阈值
    public static int DISINFECTANT_CAPACITY_THRESHOLD = 5000 / 4;

    // 短信发送模板Id
    private static final int REPLENISH_TEMPLETE_ID = 965897;

    // 补货列表查询sql
    private static final String REPLENISH_LIST_QUERY = "select d.wash_point_id,d.concrete_position_id,d.device_name,d.device_type,d.belong_merchant_name,d.wash_point_name,d.imei,d.online,r.laundry_detergent,r.replenish_status,r.disinfectant " +
            "from replenish r left join device d on d.imei=r.imei " +
            "left join wash_point wp on d.wash_point_id = wp.id " +
            "where product_type='LIQUID_PUMP' and d.user_id is not null ";

    private static final String REPLENISH_LOG_QUERY = "select d.device_name,d.device_type,d.belong_merchant_name,wp.name,r.create_time create_time,r.creator_name,r.liquid_type,r.last_capacity " +
            "from replenish_log r left join device d on d.imei=r.imei " +
            "left join wash_point wp on d.wash_point_id = wp.id " +
            "where product_type='LIQUID_PUMP' and d.user_id is not null ";

    private static final String STATUS_COUNT = "select replenish_status,count(*) count from replenish r left join device d on r.imei= d.imei  #WHERE# group by replenish_status";

    @Override
    public Replenish findByImei(String imei) {
        Optional<Replenish> optional = replenishRepo.findById(imei);
        if(optional.isPresent()){
            return optional.get();
        }
        return null;
    }

    @Override
    public BaseResult list(ReplenishVO replenishVO) {
        checkPageNum(replenishVO.getPageNum());
        String sql = buildSql(replenishVO);
        PageResult<ReplenishDTO> pageResult = replenishRepo.findNativeNamedQuery(sql, PageRequest.of(replenishVO.getPageNum(), replenishVO.getPageSize()), ReplenishDTO.class);
        List<ReplenishDTO> elements = pageResult.getElements();
        if(CollectionUtil.isNotEmpty(elements)){
            elements.forEach(e ->{
                if(StringUtils.isNotBlank(e.getConcretePositionId())){
                    Optional<WashPointConcretePositionEntity> byId = positionEntityRepo.findById(e.getConcretePositionId());
                    if(byId.isPresent()){
                        e.setBuilding(byId.get().getBuilding());
                        e.setFloor(byId.get().getFloor());
                        e.setRoom(byId.get().getRoom());
                    }
                }
                e.setLaundryDetergent(e.getLaundryDetergent() < 0 ? 0 : e.getLaundryDetergent());
                e.setDisinfectant(e.getDisinfectant() < 0 ? 0 : e.getDisinfectant());
                Optional<LiquidCapacitySetting> setting = liquidCapacitySettingRepo.findById(e.getWashPointId());
                if(setting.isPresent()){
                    e.checkOperation(setting.get().getLThreshold(),setting.get().getDThreshold());
                    e.setLDefaultSize(setting.get().getLCapacity()).setDDefaultSize(setting.get().getDCapacity());
                }else{
                    e.setLDefaultSize(LAUNDRY_DETERGENT_CAPACITY).setDDefaultSize(DISINFECTANT_CAPACITY);
                    e.checkOperation(LAUNDRY_DETERGENT_CAPACITY_THRESHOLD,DISINFECTANT_CAPACITY_THRESHOLD);
                }
            });
        }
        return BaseResultFactory.produceSuccess(pageResult);
    }

    private void checkPageNum(int pageNum) {
        if (pageNum < 1) {
            log.error("分页查询异常，页码小于1");
            throw new BusinessException(Code.PARAMETER_ERROR);
        }
    }

    /**
     * 补充完库存容量后，更新状态
     * @param imei
     * @param liquidType
     * @return
     */
    @Override
    public BaseResult updateStock(String imei,Integer liquidType,Integer size) {
        log.info("更新{}{}库存使用容量",imei,liquidType);
        try {
            ReplenishLog replenishLog = new ReplenishLog().setImei(imei).setLiquidType(liquidType.toString());
            Replenish replenish = replenishRepo.findById(imei).orElseThrow(() -> new BusinessException(Code.NODATA));
            DeviceEntity deviceEntity = deviceEntityRepo.findByImei(imei);
            if(deviceEntity == null){
                throw new BusinessException(Code.NODATA);
            }
            int leftCapacity = 0;
            if(liquidType == 1){// 洗衣液
                replenishLog.setLastCapacity(replenish.getLaundryDetergent());
                replenish.setLaundryDetergent(size);
                leftCapacity = replenish.getDisinfectant();
            }else if(liquidType == 2){
                replenishLog.setLastCapacity(replenish.getDisinfectant());
                replenish.setDisinfectant(size);
                leftCapacity = replenish.getDisinfectant();
            }
            replenish.setReplenishStatus(ReplenishStatus.getTypeByCode(getStatus(leftCapacity,liquidType,ReplenishStatus.FULL.getCode(), imei)));
            UserEntity merchant = userRelService.getUserMerchant(AuthenticationHolder.getUserId());
            replenishLog.setMerchantId(merchant.getId()).setOperName(merchant.getUsername());
            replenishRepo.save(replenish);
            repleinshLogRepo.save(replenishLog);
        } catch (BusinessException e) {
            log.error("补货更新出现错误{}",e);
        }
        return BaseResultFactory.produceSuccess();
    }

    @Override
    public BaseResult logList(ReplenishLogVO replenishVO) {
        checkPageNum(replenishVO.getPageNum());
        String sql = buildSql(replenishVO);
        PageResult<ReplenishLogDTO> pageResult = replenishRepo.findNativeNamedQuery(sql, PageRequest.of(replenishVO.getPageNum(), replenishVO.getPageSize()), ReplenishLogDTO.class);
        List<ReplenishLogDTO> elements = pageResult.getElements();
        int defaultLCapacity = LAUNDRY_DETERGENT_CAPACITY,defaultDCapacity = DISINFECTANT_CAPACITY;
        if(StringUtils.isNotBlank(replenishVO.getWashPointId())){
            Optional<LiquidCapacitySetting> setting = liquidCapacitySettingRepo.findById(replenishVO.getWashPointId());
            if(setting.isPresent()){
                defaultLCapacity = setting.get().getLCapacity();
                defaultDCapacity = setting.get().getDCapacity();
            }
        }
        if(CollectionUtil.isNotEmpty(elements)){
            int finalDefaultLCapacity = defaultLCapacity;
            int finalDefaultDCapacity = defaultDCapacity;
            elements.forEach(e ->{
                e.setCurrentCapacity(StringUtils.equals(e.getLiquidType(),"1") ? finalDefaultLCapacity : finalDefaultDCapacity);
                e.setLastCapacity(e.getLastCapacity() < 0 ? 0 : e.getLastCapacity());
            });
        }
        return BaseResultFactory.produceSuccess(pageResult);
    }

    @Override
    public BaseResult logExport(ReplenishLogVO replenishVO, HttpServletResponse response) {
        checkPageNum(replenishVO.getPageNum());
        String sql = buildSql(replenishVO);
        replenishVO.setPageSize(9999);
        PageResult<ReplenishLogDTO> pageResult = replenishRepo.findNativeNamedQuery(sql, PageRequest.of(replenishVO.getPageNum(), replenishVO.getPageSize()), ReplenishLogDTO.class);
        List<ReplenishLogDTO> elements = pageResult.getElements();
        int defaultLCapacity = LAUNDRY_DETERGENT_CAPACITY,defaultDCapacity = DISINFECTANT_CAPACITY;
        if(StringUtils.isNotBlank(replenishVO.getWashPointId())){
            Optional<LiquidCapacitySetting> setting = liquidCapacitySettingRepo.findById(replenishVO.getWashPointId());
            if(setting.isPresent()){
                defaultLCapacity = setting.get().getLCapacity();
                defaultDCapacity = setting.get().getDCapacity();
            }
        }
        if(CollectionUtil.isNotEmpty(elements)){
            int finalDefaultLCapacity = defaultLCapacity;
            int finalDefaultDCapacity = defaultDCapacity;
            elements.forEach(e ->{
                e.setCurrentCapacity(StringUtils.equals(e.getLiquidType(),"1") ? finalDefaultLCapacity : finalDefaultDCapacity);
                e.setLastCapacity(e.getLastCapacity() < 0 ? 0 : e.getLastCapacity());
                e.setLiquidType("1".equals(e.getLiquidType()) ? "洗衣液" : "除菌液");
                e.setDeviceType(DeviceType.getDescByName(e.getDeviceType()));
            });
        }
        try {
            ExcelUtils.exportExcel(elements, null, "补货日志信息", ReplenishLogDTO.class, "replenishLog", response);
        } catch (IOException e) {
            return BaseResultFactory.produceResult(Code.EXPORT_ERROR,e.getMessage());
        }
        return BaseResultFactory.produceSuccess();
    }

    /**
     * 消耗库存，减少库存容量
     * @param imei
     * @param capacities
     */
    @Override
    public void updateStockCapacity(String imei, List<Integer> capacities) {
        Replenish replenish = replenishRepo.findById(imei).orElseThrow(() -> new BusinessException(Code.NODATA));
        int status = ReplenishStatus.FULL.getCode();
        int laundryDetergent = 0,disinfectant = 0;
        if(CollectionUtil.isNotEmpty(capacities)){
            for (int i = 0; i < capacities.size(); i++) {
                if(i == 0){// 洗衣液
                    laundryDetergent = replenish.getLaundryDetergent() - capacities.get(0);
                    status = getStatus(laundryDetergent,1,status,imei);
                }else if(i == 1){//消毒液
                    disinfectant = replenish.getDisinfectant() - capacities.get(1);
                    status = getStatus(disinfectant, 2,status,imei);
                }
            }
        }
        log.info("设备{}库存容量状态为{},洗衣液{}，消毒液{}",imei,status,laundryDetergent,disinfectant);
        replenish.setLaundryDetergent(laundryDetergent);
        replenish.setDisinfectant(disinfectant);
        replenish.setReplenishStatus(ReplenishStatus.getTypeByCode(status));
        replenishRepo.saveAndFlush(replenish);
        if(ReplenishStatus.WAIT_REPLENISH.getCode() == status){
            try {
                log.info("补货提醒通知洗衣液剩余{}g,消毒液剩余{}g",laundryDetergent,disinfectant);
                int finalLaundryDetergent = laundryDetergent;
                int finalDisinfectant = disinfectant;
                new Thread(() -> getReplenishOperPhone(imei, finalLaundryDetergent, finalDisinfectant)).start();
            } catch (Exception e) {
                log.error("补货提醒短信发送失败{}",e);
            }
        }

    }

    private void getReplenishOperPhone(String imei,int laundryDetergent, int disinfectant){
        DeviceEntity deviceEntity = deviceEntityRepo.findByImei(imei);
        String[] params = new String[]{(laundryDetergent < 0 ? 0 : laundryDetergent) + "",(disinfectant < 0 ? 0 : disinfectant) + ""};
        if(deviceEntity != null){
            String creatorId = deviceEntity.getCreatorId();
            if(StringUtils.isNotBlank(creatorId)){
                log.info("设备创建人的Id为{}",creatorId);
                List<String> allIds = userRelEntityRepo.findAllUserByUserId(creatorId);
                List<String> allReplenishIds = userRoleEntityRepo.findAllUserIdsByRoleName("补货员");
                // 求交集
                List<String> intersection = (List<String>) CollectionUtils.intersection(allIds, allReplenishIds);
                // 交集里面将运营商剔除掉
                intersection.remove(creatorId);
                if(CollectionUtils.isEmpty(intersection)){
                    // 直接获取运营商的电话
                    intersection.add(creatorId);
                }
                log.info("用户有{}", intersection.toString());
                for (String userId : intersection) {
                    Optional<UserEntity> byId = userEntityRepo.findById(userId);
                    if(byId.isPresent()){
                        UserEntity userEntity = byId.get();
                        // 测试只允许向17600884246 发送消息
                        if(StringUtils.isNotBlank(userEntity.getPhone()) && userEntity.getEnable() /*&& "17600884246".equals(userEntity.getPhone())*/){
                            try {
                                log.info("有效用户手机号为{}",userEntity.getPhone());
                                TencentSMSUtil.sendSMSWithParams( userEntity.getPhone(), REPLENISH_TEMPLETE_ID, params);
                            } catch (Exception e) {
                                log.error("补货提醒短信发送失败{}",e);
                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    public void onlineUpdate(String deviceType, String imei) {
        log.info("洗衣机关联加液器设备，加入补货列表{}",imei);
        Replenish one = replenishRepo.findOneByProperty("imei",imei);
        if(one == null){
            one = new Replenish().setImei(imei).setLaundryDetergent(LAUNDRY_DETERGENT_CAPACITY).setDisinfectant(0).setReplenishStatus(ReplenishStatus.FULL);
            if(DeviceType.PUMP_LA_2.getName().equals(deviceType)){
                one.setDisinfectant(DISINFECTANT_CAPACITY);
            }
            replenishRepo.save(one);
        }
    }

    @Override
    public BaseResult statusCount(String deviceType,Integer replenishStatus) {
        String sql = buildStatusCountSql(STATUS_COUNT,deviceType,replenishStatus);
        List<ReplenishStatusCountDTO> list = replenishRepo.findNativeNamedQuery(sql, new Object[]{}, ReplenishStatusCountDTO.class);

        return BaseResultFactory.produceSuccess(list);
    }

    @Override
    public void deleteReplenish(String imei) {
        Optional<Replenish> replenish = replenishRepo.findById(imei);
        if(replenish.isPresent()){
            replenishRepo.deleteById(imei);
        }
    }

    @Override
    public ReplenishDTO getReplenishInfo(String imei) {
        ReplenishDTO replenishDTO = new ReplenishDTO();
        Replenish replenish = replenishRepo.findById(imei).orElseThrow(() -> new BusinessException(Code.NODATA));
        DeviceEntity byImei = deviceEntityRepo.findByImei(imei);
        if(byImei != null && byImei.getOnline() && DeviceStatus.NOT_RUNNING.equals(byImei.getStatus())){
            Optional<LiquidCapacitySetting> setting = liquidCapacitySettingRepo.findById(byImei.getWashPointId());
            if(setting.isPresent()){
                if(replenish.getLaundryDetergent() >= setting.get().getLMinCapacity()){
                    replenishDTO.setLaundryOperation(true);
                }
                if(replenish.getDisinfectant() >= setting.get().getDMinCapacity()){
                    replenishDTO.setDisinfectantOperation(true);
                }
            }else{
                if(replenish.getLaundryDetergent() > 0){
                    replenishDTO.setLaundryOperation(true);
                }
                if(replenish.getDisinfectant() > 0){
                    replenishDTO.setDisinfectantOperation(true);
                }
            }
        }
        return replenishDTO;
    }

    @Override
    public void updateReplenish(Replenish replenish) {
        replenishRepo.saveAndFlush(replenish);
    }

    @Override
    public BaseResult setting(ReplenishSettingVO settingVO) {
        List<LiquidCapacitySetting> list = new ArrayList<>();
        if(StringUtils.isBlank(settingVO.getWashPointId())){
            List<WashPointForQueryListVO> washPointList = washPointService.getWashPointList(null, null);
            if(CollectionUtils.isNotEmpty(washPointList)){
                washPointList.forEach(washPointForQueryListVO -> {
                    LiquidCapacitySetting setting = new LiquidCapacitySetting();
                    BeanUtils.copyProperties(settingVO,setting);
                    setting.setWashPointId(washPointForQueryListVO.getId());
                    list.add(setting);
                });
            }
        }else{
            LiquidCapacitySetting setting = BeanCopyUtil.copy(settingVO, LiquidCapacitySetting.class);
        }
        // 先删除后新增
        liquidCapacitySettingRepo.deleteAll(list);
        liquidCapacitySettingRepo.saveAll(list);
        return BaseResultFactory.produceSuccess();
    }

    @Override
    public BaseResult settingPage(String washPointId) {
        if(StringUtils.isBlank(washPointId)){
            List<WashPointForQueryListVO> washPointList = washPointService.getWashPointList(null, null);
            if(CollectionUtils.isNotEmpty(washPointList)){
                washPointId = washPointList.get(0).getId();
            }
        }
        Optional<LiquidCapacitySetting> byId = liquidCapacitySettingRepo.findById(washPointId);
        if(byId.isPresent()){
            return BaseResultFactory.produceSuccess(byId.get());
        }else {
            ReplenishSettingVO setting = new ReplenishSettingVO();
            setting.setlCapacity(LAUNDRY_DETERGENT_CAPACITY);
            setting.setdCapacity(DISINFECTANT_CAPACITY);
            setting.setdThreshold(DISINFECTANT_CAPACITY_THRESHOLD);
            setting.setlThreshold(LAUNDRY_DETERGENT_CAPACITY_THRESHOLD);
            return BaseResultFactory.produceSuccess(setting);
        }
    }

    private String buildStatusCountSql(String sql, String deviceType, Integer replenishStatus) {
        StringBuilder stringBuilder = new StringBuilder();
        if(StringUtils.isNotBlank(deviceType)){
            stringBuilder.append(" where d.device_type='").append(deviceType).append("'");
        }
        if(replenishStatus != null && replenishStatus.intValue() != 0){
            stringBuilder.append(" where r.replenish_status=").append(replenishStatus);
        }
        return sql.replace("#WHERE#",stringBuilder.toString());
    }

    /**
     * @param leftCapacity 剩余量
     * @param liquidType 液体类型 1：洗衣液 2消毒液
     * @param status 补货状态
     * @param imei 设备号
     * @return
     */
    private int getStatus(int leftCapacity,int liquidType,int status,String imei) {
        // 当补货状态为待补货时，直接返回
        if(ReplenishStatus.WAIT_REPLENISH.getCode() == status){
            return status;
        }
        int lThreshold = LAUNDRY_DETERGENT_CAPACITY_THRESHOLD,dThreshold = DISINFECTANT_CAPACITY_THRESHOLD,
                minLCapacity = 0 ,minDCapacity = 0;
        DeviceEntity deviceEntity = deviceEntityRepo.findByImei(imei);
        if(deviceEntity != null){
            LiquidCapacitySetting liquidCapacitySetting = liquidCapacitySettingRepo.findOneByProperty("washPointId", deviceEntity.getWashPointId());
            if(liquidCapacitySetting != null){
                lThreshold = liquidCapacitySetting.getLThreshold();
                dThreshold = liquidCapacitySetting.getDThreshold();
                minLCapacity = liquidCapacitySetting.getLMinCapacity();
                minDCapacity = liquidCapacitySetting.getDMinCapacity();
            }
        }
        // 校验剩余容量不能超过默认最大容量
        // 剩余容量大于设置的阈值容量，则设置状态为告警，当小于设置的最低容量时，则发短信通知该补货了
        if(liquidType == 1){
            if(leftCapacity <= lThreshold && leftCapacity >= minLCapacity){
                status = ReplenishStatus.ALARM.getCode();
            }else if(leftCapacity < minLCapacity){
                status = ReplenishStatus.WAIT_REPLENISH.getCode();
            }
        }else if(liquidType == 2){
            if(leftCapacity <= dThreshold && leftCapacity >= minDCapacity){
                status = ReplenishStatus.ALARM.getCode();
            }else if(leftCapacity < minDCapacity){
                status = ReplenishStatus.WAIT_REPLENISH.getCode();
            }
        }
        return status;
    }

    private String buildSql(ReplenishVO replenishVO) {
        StringBuilder builder = commonBuild(REPLENISH_LIST_QUERY, replenishVO.getValue(),replenishVO.getImei(), replenishVO.getWashPointId(),"1");
        if(StringUtils.isNotBlank(replenishVO.getMerchantId())){
            builder.append(" and wp.merchant_id ='").append(replenishVO.getMerchantId()).append("'");
        }
        if(StringUtils.isNotBlank(replenishVO.getOnline())){
            builder.append(" and d.online =").append(replenishVO.getOnline());
        }
        if(StringUtils.isNotBlank(replenishVO.getDeviceType())){
            builder.append(" and d.device_type='").append(replenishVO.getDeviceType()).append("'");
        }
        if(replenishVO.getReplenishStatus() != null && replenishVO.getReplenishStatus() != 0){
            builder.append(" and r.replenish_status=").append(replenishVO.getReplenishStatus());
        }
        return builder.toString();
    }

    /**
     *
     * @param replenishListQuery 查询sql
     * @param value 模糊匹配查询值
     * @param imei 查询imei
     * @param washPointId 洗衣点ID
     * @param type 是补货列表查询还是补货日志列表查询 ，给定空值的时候 是补货日志查询
     * @return
     */
    private StringBuilder commonBuild(String replenishListQuery,String value, String imei, String washPointId,String type) {
        StringBuilder builder = new StringBuilder(replenishListQuery);
        if(StringUtils.isNotBlank(imei)){
            builder.append(" and d.imei ='").append(imei).append("'");
        }
        if(StringUtils.isNotBlank(washPointId)){
            builder.append(" and wp.id ='").append(washPointId).append("'");
        }
        if(AuthenticationHolder.isReplenish()){
            String userId = AuthenticationHolder.getUserId();
            UserEntity merchant = userRelService.getUserMerchant(userId);
            builder.append(" and wp.merchant_id ='").append(merchant.getId()).append("'");
        }else if(AuthenticationHolder.isMerchant()){
            Boolean viewAllData = AuthenticationHolder.getUserAuth().getViewAllData();
            if (viewAllData) {
                String userId = AuthenticationHolder.getUserId();
                UserEntity merchant = userRelService.getUserMerchant(userId);
                builder.append(" and wp.merchant_id ='").append(merchant.getId()).append("'");
            } else{
                Set<String> allSub = userRelService.getDescendantIds(AuthenticationHolder.getUserId());
                allSub.add(AuthenticationHolder.getUserId());
                builder.append(" and wp.merchant_id in(").append(buildInSQL(allSub)).append(")");
            }
        }
        if(StringUtils.isNotBlank(value)){
            // 设备名称以及运营商名称 模糊匹配
            builder.append(" and (d.device_name like '%").append(value)
                    .append("%' ").append(" or d.belong_merchant_name like '%").append(value).append("%'");
            if(StringUtils.isBlank(type)){
                // 补货日志搜索时 搜索补货员名称
                builder.append(" or r.creator_name like '%").append(value).append("%')");
            }else{
                builder.append(")");
            }
        }
        return builder;
    }

    private String buildInSQL(Collection<String> list){
        StringBuilder builder = new StringBuilder();
        if(CollectionUtil.isNotEmpty(list)){
            for (String str :
                    list) {
                builder.append("'").append(str).append("',");
            }
        }
        return builder.substring(0,builder.lastIndexOf(","));
    }

    private String buildSql(ReplenishLogVO replenishVO) {
        StringBuilder builder = commonBuild(REPLENISH_LOG_QUERY, replenishVO.getValue(),replenishVO.getImei(), replenishVO.getWashPointId(),"");
        if(StringUtils.isNotBlank(replenishVO.getStartDate())){
            builder.append(" and r.create_time >='").append(DateUtil.stringToLong(replenishVO.getStartDate(),"yyyy-MM-dd HH:mm:ss")).append("'");
        }
        if(StringUtils.isNotBlank(replenishVO.getEndDate())){
            builder.append(" and r.create_time <='").append(DateUtil.stringToLong(replenishVO.getEndDate(),"yyyy-MM-dd HH:mm:ss")).append("'");
        }
        if(StringUtils.isNotBlank(replenishVO.getOper())){
            builder.append(" and (r.merchant_id ='").append(replenishVO.getOper()).append("' or r.oper_name like '%")
                    .append(replenishVO.getOper()).append("%')");
        }
        if(StringUtils.isNotBlank(replenishVO.getLiquidType())){
            builder.append(" and r.liquid_type ='").append(replenishVO.getLiquidType()).append("'");
        }
        builder.append(" order by create_time desc ");
        return builder.toString();
    }

    public static void main(String[] args) throws Exception {
        // 将字符串时间转换为纳秒值
        System.out.println(DateUtil.stringToLong("2021-05-21","yyyy-MM-dd"));
        /*String[] params = new String[]{"5","10"};
        TencentSMSUtil.sendSMSWithParams("17356681385", REPLENISH_TEMPLETE_ID, params);*/
        List<String> objects = new ArrayList<>();
        objects.remove("122");
    }
}
